<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
    <meta content="initial-scale=1.0,user-scalable=no,maximum-scale=1" media="(device-height: 568px)" name="viewport">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta content="telephone=no" name="format-detection">
    <title>{$vote.title}</title>
    <link href="http://cdn.staticfile.org/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="//res.wx.qq.com/open/libs/weui/1.1.2/weui.min.css"/>
    
    <link rel="stylesheet" type="text/css" href="__CSS__/activity.css?{:rand()}"/>
    
    <script>
		var vote = {$vote_json};
		var items = {$items_json};
		var have_voted = {$vote.have_voted|default='true'};
		var records = {$records_json|default=''};
		var in_wechat = {:in_wechat('str')};
		var is_login = {$is_login};
		var uid = {$uid|default=0};
		var message ={ vote_confirm:"{$vote.dialog|default='确认要操作吗？'}"};

    </script>
</head>
<body>

<div class="container" id="container">
    
    <div class="weui-tab">
        <div class="weui-tab__panel">
            
            <!--页面 1-->
            <div id="page_1" class="page-main" data-top="0">
                <div class="banner">
                    <img class="banner" src="{$vote.banner|get_cover='path'}">
                </div>
                <div class="weui-panel__hd vote-panel">
                    <div class="page__bd">
                        <!--搜索栏-->
                        <div class="weui-search-bar" id="searchBar">
                            <form class="weui-search-bar__form">
                                <div class="weui-search-bar__box">
                                    <i class="weui-icon-search"></i>
                                    <input type="search" class="weui-search-bar__input" id="searchInput" placeholder="输入姓名或编号" required="">
                                    <a href="javascript:" class="weui-icon-clear" id="searchClear"></a>
                                </div>
                                <label class="weui-search-bar__label" id="searchText" style="transform-origin: 0 0 0; opacity: 1; transform: scale(1, 1);">
                                    <i class="weui-icon-search"></i>
                                    <span>搜索</span>
                                </label>
                            </form>
                            <a href="javascript:" class="weui-search-bar__cancel-btn" id="searchCancel">取消</a>
                        </div>
                        <!--/搜索栏-->


                        <!--搜索提示栏-->
                        <div class="weui-cells searchbar-result" id="searchResult" style="transform-origin: 0px 0px 0px; opacity: 1; transform: scale(1, 1); display: none;">
                            <div class="weui-cell weui-cell_access">
                                <div class="weui-cell__bd weui-cell_primary">
                                    <p>实时搜索文本</p>
                                </div>
                            </div>
                            <div class="weui-cell weui-cell_access">
                                <div class="weui-cell__bd weui-cell_primary">
                                    <p>实时搜索文本</p>
                                </div>
                            </div>
                            <div class="weui-cell weui-cell_access">
                                <div class="weui-cell__bd weui-cell_primary">
                                    <p>实时搜索文本</p>
                                </div>
                            </div>
                            <div class="weui-cell weui-cell_access">
                                <div class="weui-cell__bd weui-cell_primary">
                                    <p>实时搜索文本</p>
                                </div>
                            </div>
                        </div>
                        <!--/搜索提示栏-->
                        
                        <!--活动数据面板-->
                        <div class="weui-grids weui-grids-vote">
                            <div class="weui-grid">
                                <p class="weui-grid__label">参赛人数</p>
                                <p class="weui-grid__label label-item-number">{$vote.item_number}</p>
                            </div>
                            <div class="weui-grid">
                                <p class="weui-grid__label">投票人次</p>
                                <p class="weui-grid__label label-vote-number">{$vote.vote_number}</p>
                            </div>
                            <div class="weui-grid">
                                <p class="weui-grid__label">访问量</p>
                                <p class="weui-grid__label label-vote-view">{$vote.view}</p>
                            </div>
                        </div>
                        <!--/活动数据面板-->
                        <div class="vote-status">
                        </div>

                    </div>
                </div>
                
                <div class="weui-panel__bd vote-sub-page">
                    <div class="weui-tab">
                        
    
    
                        <!--导航-->
                        <div class="weui-navbar vote-nav" style="">
                            <div class="weui-navbar__item weui-bar__item_on" data-page-id="page_1_1" data-action="getNew">
                                <span class="vote-nav-btn">
                                    最新参赛
                                </span>
                            </div>
                            <div class="weui-navbar__item" data-page-id="page_1_2" data-action="getOrder">
                                <span class="vote-nav-btn">
                                    投票排行
                                </span>
                            </div>
                            <div class="weui-navbar__item" data-page-id="page_1_3" data-action="getTop10">
                                <span class="vote-nav-btn">
                                    TOP10
                                </span>
                            </div>
                        </div>
                        <!--/导航-->
                        
                        <!--页面 1 的子页面-->
                        <div class="weui-tab__panel">
                            
                            <!--页面 1.1-->
                            <div id="page_1_1" class="page-sub">
                                <div class="waterfall">
                                    <div class="fall">
                                    </div>
                                    <div class="fall">
                                    </div>
                                </div>
                                <!--<div class="weui-loadmore">-->
                                    <!--<i class="weui-loading"></i>-->
                                    <!--<span class="weui-loadmore__tips">正在加载</span>-->
                                <!--</div>-->
                                <!--<div class="weui-loadmore weui-loadmore_line">-->
                                    <!--<span class="weui-loadmore__tips">暂无数据</span>-->
                                <!--</div>-->
                                <!--<div class="weui-loadmore weui-loadmore_line weui-loadmore_dot">-->
                                    <!--<span class="weui-loadmore__tips"></span>-->
                                <!--</div>-->
                            </div>
                            <!--/页面 1.1-->
                            
                            <!--页面 1.2-->
                            <div id="page_1_2" class="page-sub"></div>
                            <!--/页面 1.2-->
                            
                            <!--页面 1.3-->
                            <div id="page_1_3" class="page-sub"></div>
                            <!--/页面 1.3-->
    
                            <!--页面 1.4-->
                            <div id="page_1_4" class="page-sub"></div>
                            <!--/页面 1.4-->
    
                            <!--页面 1.5-->
                            <div id="page_1_5" class="page-sub"></div>
                            <!--/页面 1.5-->
                            
                        </div>
                        <!--/页面 1 的子页面-->
                        
                    </div>
                </div>
            </div>
            <!--/页面 1-->
            
            <!--页面 2-->
            <div id="page_2" class="page-main">
     2
            </div>
            <!--/页面 2-->
            
            <!--页面 3-->
            <div id="page_3" class="page-main">
                <article class="weui-article">
                    <h1>{$vote.title} 活动说明</h1>
                    <section>
                        {$vote.illustrate}
                    </section>
                </article>
            </div>
            <!--/页面 3-->
            
            <!--页面 4-->
            <div id="page_4" class="page-main">
                <article class="weui-article">
                    <h1>{$vote.title} 奖品说明</h1>
                    <section>
                        {$vote.prise}
                    </section>
                </article>
            </div>
            <!--/页面 4-->
    
            <!--页面 5-->
            <div id="page_5" class="page-main">
            </div>
            <!--/页面 4-->
            
            
            <!--版权信息-->
            <div id="footer" class="weui-footer">
                <p class="weui-footer__links">
                    <a href="http://www.huiyou365.net" class="weui-footer__link">Powered by 汇友科技</a>
                    <a href="tel:{:C('PHONE')}" class="weui-footer__link">{:C('PHONE')}</a>
                </p>
                <p class="weui-footer__text">Copyright © 2015-2017 huiyou365.net</p>
            </div>
            <!--/版权信息-->
            
        </div>
        
        <!--底部导航-->
        <div id="tabbar" class="weui-tabbar main_nav">
            <a href="javascript:;" class="weui-tabbar__item weui-bar__item_on" data-page-id="page_1" data-page-name="home" data-page-title="{$vote.title}" data-action="getNew">
                <i class="weui-tabbar__icon fa fa-home"></i>
                <p class="weui-tabbar__label">首页</p>
            </a>
            <a href="javascript:;" class="weui-tabbar__item" data-page-id="page_2" data-page-name="chart" data-page-title="排行" data-action="getOrder">
                <i class="weui-tabbar__icon fa fa-user-plus"></i>
                <p class="weui-tabbar__label">排名</p>
            </a>
            <a href="javascript:;" class="weui-tabbar__item" data-page-id="page_3" data-page-name="illustrate" data-page-title="说明">
                <i class="weui-tabbar__icon fa fa-plane"></i>
                <p class="weui-tabbar__label">说明</p>
            </a>
            <a href="javascript:;" class="weui-tabbar__item" data-page-id="page_4" data-page-name="prise" data-page-title="奖品">
                <i class="weui-tabbar__icon fa fa-trophy"></i>
                <p class="weui-tabbar__label">奖品</p>
            </a>
        </div>
        <!--/底部导航-->
        
    </div>
    
    <div id="notice" style="display: none;">
        <div class="weui-mask"></div>
        <div class="weui-dialog">
            <div class="weui-dialog__hd"><strong class="weui-dialog__title">弹窗标题</strong></div>
            <div class="weui-dialog__bd">弹窗内容，告知当前页面信息等</div>
            <div class="weui-dialog__ft">
                <a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_primary">确定</a>
            </div>
        </div>
    </div>
    <div id="dialog" style="display: none;">
        <div class="weui-mask"></div>
        <div class="weui-dialog">
            <div class="weui-dialog__hd"><strong class="weui-dialog__title">确定要投票吗？</strong></div>
            <div class="weui-dialog__bd"></div>
            <div class="weui-dialog__ft">
                <a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_default dialog-cancel">取消</a>
                <a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_primary dialog-yes">确认</a>
            </div>
        </div>
    </div>
    <div id="toast" style="display: none;">
        <div class="weui-mask_transparent"></div>
        <div class="weui-toast">
            <i class="weui-icon-success-no-circle weui-icon_toast"></i>
            <p class="weui-toast__content">已完成</p>
        </div>
    </div>
    <div id="loadingToast" style="display:none;">
        <div class="weui-mask_transparent"></div>
        <div class="weui-toast">
            <i class="weui-loading weui-icon_toast"></i>
            <p class="weui-toast__content">数据加载中</p>
        </div>
    </div>
</div>
<script src="http://cdn.staticfile.org/jquery/3.2.1/jquery.min.js" type="application/javascript"></script>
<script src="http://cdn.staticfile.org/zepto/1.0rc1/zepto.min.js" type="application/javascript"></script>
<script>
    $(function(){
        var
            body = $("body"),
            container = $("#container"),
            banner = $(".banner"),
            refresh_time = {$refresh_time|default=3},
            refresh_prob = {$refresh_prob|default=0.5},
            refresh = Date.parse(new Date())/1000,
            label_item_number = $(".label-item-number"),
            label_vote_number = $(".label-vote-number"),
            label_vote_view = $(".label-vote-view"),
            loadingToast = $("#loadingToast"),
            textToast = $("#toast"),
            dialog = $("#dialog"),
            notice = $("#notice"),
                vote_status = $(".vote-status"),
            pages_main = $(".page-main"),
            pages_sub = $(".page-sub"),
            page_sub_nav = $("[data-page-id^='page_1_']"),
            page_sub_nav_1 = $("[data-page-id='page_1_1']"),
            page_sub_nav_2 = $("[data-page-id='page_1_2']"),
            page_sub_nav_3 = $("[data-page-id='page_1_3']"),
            page_main_nav = $(".main_nav [data-page-id^='page_']"),
            page_main_nav_1 = $(".main_nav [data-page-id='page_1']"),
            page_main_nav_2 = $(".main_nav [data-page-id='page_2']"),
            page_main_nav_3 = $(".main_nav [data-page-id='page_3']"),
            page_main_nav_4 = $(".main_nav [data-page-id='page_4']"),
            page_1_1 = $("#page_1_1"),
            page_1_2 = $("#page_1_2"),
            page_1_3 = $("#page_1_3"),
            page_1_4 = $("#page_1_4"),
            page_1_5 = $("#page_1_5"),
            page_1 = $("#page_1"),
            page_2 = $("#page_2"),
            page_3 = $("#page_3"),
            page_4 = $("#page_4"),
            page_5 = $("#page_5"),
            waterfall = $(".waterfall"),
            page_current;


        // 模板渲染
        var template_item_big = function (data, callback){
            return $('<div class="weui-media-box weui-media-box_appmsg vote-item">'+
                '<div class="weui-media-box__hd vote-item-cover">'+
                '<a href="javascript:;" class="item-detail" data-item-id="'+data.id+'">'+
                '<img class="weui-media-box__thumb" src="'+data.path+'" alt="">'+
                '<div class="vote-item-cover-number">'+
                data.number+' 号'+
                '</div>'+
                '</a>'+
                '</div>'+
                '<div class="weui-media-box__bd vote-item-title">'+
                '<h4 class="weui-media-box__title">'+data.title+'</h4>'+
                '<span class="vote-item-votes"><span data-item-vote-id="'+data.id+'"">'+data.vote+'</span> 票</span>'+
                '<button class="weui-btn weui-btn_mini weui-btn_primary vote-item-button" data-item-id="'+data.id+'" data-item-vote="'+data.vote+'">投票</button>'+
                '</div>'+
                '</div>');
        };
        var template_item_waterfall = function (data, callback){
            var falls = waterfall.children(".fall"),
                min = {height: 0, index:0};
            
            for( var i=0; i< falls.length; i++){
                var fall = $(falls[i]);
                fall.maxHeight = 0;
                var drops = fall.children(".vote-item");
                for (var j=0; j <drops.length; j++) {
                    var drop = $(drops[j]);
                    fall.maxHeight += parseInt(drop.height());
                }
                if (i === 0) {
                    min.height = fall.maxHeight;
                    min.index = i;
                }
                if (fall.maxHeight < min.height) {
                    min.height = fall.maxHeight;
                    min.index = i;
                }
                
            }
            
            var template = $('<div class="weui-media-box weui-media-box_appmsg vote-item">'+
                '<div class="weui-media-box__hd vote-item-cover">'+
                '<a href="javascript:;" class="item-detail" data-item-id="'+data.id+'">'+
                '<img class="weui-media-box__thumb" src="'+data.path+'" alt="">'+
                '<div class="vote-item-cover-number">'+
                data.number+' 号'+
                '</div>'+
                '</a>'+
                '</div>'+
                '<div class="weui-media-box__bd vote-item-title">'+
                '<h4 class="weui-media-box__title"><span class="vote-item-votes"><span data-item-vote-id="'+data.id+'"">'+data.vote+'</span> 票</span><span class="number">第1号</span><span class="title">'+data.title+'</span></h4>'+
                ''+
                '<button class="weui-btn weui-btn_mini weui-btn_primary vote-item-button" data-item-id="'+data.id+'" data-item-vote="'+data.vote+'">投票</button>'+
                '</div>'+
                '</div>');
            $(falls[min.index]).append(template);
        };
        var template_item_small = function (data, callback){
            return $('<div class="weui-media-box weui-media-box_appmsg item-detail" data-item-id="'+data.id+'" >' +
                '<div class="weui-media-box__hd vote-item-cover-small" style="background-image:url(' + data.path + ');background-size:cover;">' +
//                                            '<img class="weui-media-box__thumb" src="'+data.path+'" alt="">'+
                '<style>.vote-item-cover-number-small[data-item-id="' + data.id + '"]:after{background-image:url(' + data.path + ')}</style>' +
                '<div class="vote-item-cover-number-small" data-item-id="' + data.id + '">' + data.id + '</div>' +
                '</div>' +
                '<div class="weui-media-box__bd">' +
                '<h4 class="weui-media-box__title" style="color:#f00;">第' + data.ranking + '名</h4>' +
                '<p class="weui-media-box__desc">第' + data.number + '号 ' + data.title + ' <span data-item-vote-id="'+data.id+'" data-votes="'+data.vote+'">' + data.vote + '</span> 票</p>' +
                '</div>' +
                '</div>');
        };
        var template_item_small_result = function (data, callback){
            return $('<div class="weui-media-box weui-media-box_appmsg item-detail" data-item-id="'+data.id+'" >' +
                '<div class="weui-media-box__hd vote-item-cover-small" style="background-image:url(' + data.path + ');background-size:cover;">' +
//                                            '<img class="weui-media-box__thumb" src="'+data.path+'" alt="">'+
                '<style>.vote-item-cover-number-small[data-item-id="' + data.id + '"]:after{background-image:url(' + data.path + ')}</style>' +
                '<div class="vote-item-cover-number-small" data-item-id="' + data.id + '">' + data.id + '</div>' +
                '</div>' +
                '<div class="weui-media-box__bd">' +
                '<h4 class="weui-media-box__title" style="color:#f00;">第' + data.number + '号</h4>' +
                '<p class="weui-media-box__desc">' + data.title + ' <span data-item-vote-id="'+data.id+'" data-votes="'+data.vote+'">' + data.vote + '</span> 票</p>' +
                '</div>' +
                '</div>');
        };
        var template_item_detail = function (data, callback){
            var ele = $('<article class="weui-article">' +
                '<h1>' + data.title + '</h1>' +
                '<section>' +
                data.content +
                '</section>' +
                '<a href="javascript:;" class="weui-btn weui-btn_primary vote-item-button" data-item-id="'+data.id+'" data-item-vote="'+data.vote+'" style="float: none;">投票</a>' +
                '<a href="javascript:;" class="weui-btn weui-btn_default page-back">返回</a>' +
                '</article>');
            var back = ele.find(".page-back");
            back.off('click');
            back.on('click',function(){
                callback(back);
            });
            return ele;
        };
        var template_item_result = function (data, callback) {
            return $('<div class="weui-cell weui-cell_access item-detail" data-item-id="' + data.id + '" >' +
                '<div class="weui-cell__bd weui-cell_primary">' +
                '<p>' + data.number + '号 ' + data.title + '</p>' +
                '</div>' +
                '</div>');
        };



        (function(){
            // 活动状态
             var status = window.setInterval(function(){
                var msg = {}, days, hours, minutes, seconds;
                var now = Date.parse(new Date())/1000;
                var pieces = {title:'', days:'天', hours:'小时',minutes:'分钟',seconds:'秒'};
                if ((now - vote.start) < 0) {
                    msg.title = '距离开始还有';
                    days = Math.floor((vote.start - now)/(24*3600));
                    hours = Math.floor((vote.start - now)%(24*3600)/3600);
                    minutes = Math.floor((vote.start - now)%3600/60);
                    seconds = Math.floor((vote.end - now)%60);
                    if (days > 0) {
                        msg.days = days;
                    }
                    if (hours > 0) {
                        msg.hours = hours;
                    }
                    if (minutes > 0) {
                        msg.minutes = minutes;
                    }
                    msg.seconds = seconds;
                } else if ((now - vote.end) > 0) {
                    msg.title = '活动已经结束';
                    window.clearInterval(status);
                    alert({title:'抱歉',body:'活动已结束'});
                } else {
                    msg.title = '距离结束还有';
                    days = Math.floor((vote.end - now)/(24*3600));
                    hours = Math.floor((vote.end - now)%(24*3600)/3600);
                    minutes = Math.floor((vote.end - now)%3600/60);
                    seconds = Math.floor((vote.end - now)%60);
                    if (days > 0) {
                        msg.days = days;
                    }
                    if (hours > 0) {
                        msg.hours = hours;
                    }
                    if (minutes > 0) {
                        msg.minutes = minutes;
                    }
                    msg.seconds = seconds;
                    
                }
                // 生成元素
                 vote_status.html('');
                 for (var k in msg) {
                     vote_status.append($('<span class="status-time" data-name="'+k+'">'+msg[k]+'</span>'));
                     vote_status.append($('<span>'+pieces[k]+'</span>'));
                 }
            },1000);
             
             // 填充内容
            getNew();
            
        })();
        
        // 底部导航按钮
        $(".weui-tabbar__item").on("click", function(){
            var that = this,
                page_id = $(this).data("page-id"),
                page_name = $(this).data("page-name"),
                page_title = $(this).data("page-title"),
                action = $(this).data("action"),
                callback;
            
            // 刷新数据
            getData();
            
            pages_main.hide();
            $(this).siblings().removeClass("weui-bar__item_on");
            $(this).addClass("weui-bar__item_on");

            callback = function (){
                // 显示页面
                loading(false,'');
                $("#"+page_id).show();
                $(that).siblings().removeClass("weui-bar__item_on");
                $(that).addClass("weui-bar__item_on");
            };

            switch(action) {
                case "getOrder":
                    getOrder(callback);
                    break;
                case "getTop10":
                    getTop10(callback);
                    break;
                case "getNew":
                    getNew(callback);
                    break;
                default:
                    $("#"+page_id).show();
                    addHistory({"page":page_name}, page_title, "#page="+page_name);
            }
            
            // 增加历史
        });

        // 顶部导航按钮
        $(".weui-navbar__item").on("click", function(){
            var that = this,
                page_id = $(this).data("page-id"),
                action = $(this).data("action");
            
            // 刷新数据
            getData();
            
            // 隐藏全部页面
            pages_sub.hide();
            // 显示加载动画
            loading(true,'加载中');
            // 执行绑定函数
            var callback = function (){
                // 显示页面
                loading(false,'');
                $("#"+page_id).show();
                $(that).siblings().removeClass("weui-bar__item_on");
                $(that).addClass("weui-bar__item_on");
            };
            switch(action) {
                case "getOrder":
                    getOrder(callback);
                    break;
                case "getTop10":
                    getTop10(callback);
                    break;
                case "getNew":
                    getNew(callback);
                    break;
            }
        });
        

        // 投票事件
        body.on("click", ".vote-item-button", function(){
            var that = $(this),
                callback, // 投票执行函数
                item_id = $(this).data("item-id"),
                item_vote = $(this).data("item-vote"),// 投票按钮的票数
                data = {action:'vote', vote_id:vote.id, item_id:item_id, uid:uid}; // 请求参数
            
            var now = Date.parse(new Date())/1000,
                msg = {title:'抱歉！', body: '不能投票'},
                can_vote = true;
            
            // 检查是否可以投票
            // 检验时间
            if ((now - vote.start) < 0) {
                msg.body = '活动还未开始';
                can_vote = false;
            } else if ((now - vote.end) > 0) {
                msg.body = '活动已经结束';
                can_vote = false;
            }
            // 判断是否登录
            if (!is_login || !(uid > 0)) {
                msg.body = '您还未登录';
                can_vote = false;
            }
            
            // 0点时间
            var today = new Date();
            today.setHours();
            today.setMinutes(0);
            today.setSeconds(0);
            today.setMilliseconds(0);
            switch (parseInt(vote.type)) {
                case 1:
                    // 每个选项可投票一次
                    for (var k in records) {
                        if (parseInt(records[k].item_id) === parseInt(item_id)) {
                            msg.body = '每个选项可投票一次,已经投过票了';
                            can_vote = false;
                            break;
                        }
                    }
                    break;
                case 2:
                    // 每天可投票一次
                    for (var k in records) {
                        if (records[k].created_at >= Date.parse(today)/1000) {
                            msg.body = '今天已经投过票了';
                            can_vote = false;
                            break;
                        }
                    }
                    break;
                case 3:
                    // 每天可为每个选项投一票
                    for (var k in records) {
                        if (parseInt(records[k].item_id) === (item_id) && records[k].created_at >= Date.parse(today)/1000) {
                            msg.body = '今天已经投过票了';
                            can_vote = false;
                            break;
                        }
                    }
                    break;
                case 0:
                default:
                    if (records) {
                        msg.body = '只有一次机会，已经投过票了';
                        can_vote = false;
                    }
            }
            if (!can_vote) {
                alert(msg);
                return false;
            }
            // 投票执行函数
            callback = function(){
                // 加载动画
                loading(true, "投票中");
                
                // 请求
                $.get(
                    '/index.php/Vote/api',
                    data,
                    function (res) {
                        
                        // 停止动画
                        loading(false);
                        
                        // 判断投票状态
                        if (0 === res.error) {
                            toast(true,'投票成功');
                            item_vote ++;
                            that.data("item-vote", item_vote);
                            $("[data-item-vote-id='"+ item_id +"']").text(item_vote);
                            $("[data-item-vote='"+ item_id +"']").text(item_vote);
                            
                            // 刷新数据
                            records = res.data.records;
                            items = res.data.items;
                            vote = res.data.vote;

                            for(var i in items) {
                                if (parseInt(item_id) === parseInt(items[i].id)) {
                                    items[i].vote ++;
                                    break;
                                }
                            }
                            freshData();
                            have_voted = true;
                        } else {
                            var text = '';
                            switch(res.error) {
                                case 2:
                                    text = '未登录';
                                    break;
                                case 5:
                                    text = '活动还未开始';
                                    break;
                                case 6:
                                    text = '活动已经结束';
                                    break;
                                case 7:
                                    text = '已经投过票了';
									have_voted = true;
                                    break;
                                default:
                                    text = '投票失败';
                            }
                            
                            // 提示投票失败
                            toast(false, res.msg);
                        }
                    }).fail(function(res){
					    // 关闭加载动画
					    loading(false);
					});
            };

            // 确认对话框
            confirm(
                {title:'确认要投票吗？',body:message.vote_confirm},
                callback,
                null
            );
        });
        
        // 选项详情按钮
        body.on("click", ".item-detail", function(){
            var item_id = $(this).data("item-id"), item,  calback;
            if (!item_id){
                // 提示窗口
                alert({title:"抱歉！", body:"无详细内容"});
                return null;
            }
            for(var i in items){
                if (parseInt(item_id) === parseInt(items[i].id)) {
                    // 查找当前显示窗口
                    pages_sub.each(function(i){
                        if ("block" === $(pages_sub[i]).css("display")) {
                            page_current = $(pages_sub[i]);
                            // 隐藏当前显示窗口
                            page_current.hide();
                            return false;
                        }
                    });
                    // 创建回调函数
                    callback = function(that) {
                        // 返回
                        history.back();
                    };
                    // 创建并填充元素
                    add_item(page_5, items[i], template_item_detail, true, true, callback);


                    // 隐藏页面
                    pages_main.hide();
                    // 显示详情页面
                    page_5.show();
                    
                    // 增加页面历史
                    addHistory({"page": "detail"}, items[i].title,"#detail="+item_id);
                    
                    // 修改样式
//                    page_sub_nav.removeClass("weui-bar__item_on");
                    break;
                }
            }
        });
        
        
        // 通知框
        function alert(data, origin){
            if (origin) {
                window.alert(data);
            } else {
                notice.find(".weui-dialog__btn").on("click", function(){
                    notice.find(".weui-dialog__btn").off("click");
                    notice.hide();
                });
                notice.find(".weui-dialog__title").html(data.title);
                notice.find(".weui-dialog__bd").html(data.body);
                notice.show();
            }
        }
        
        // Toast消息
        function toast(type, text, time) {
            if (!type) {
                textToast.find(".weui-icon_toast").removeClass("weui-icon-success-no-circle").addClass("weui-icon-cancel");
            } else {
                textToast.find(".weui-icon_toast").removeClass("weui-icon-cancel").addClass("weui-icon-success-no-circle");
            }
            textToast.find(".weui-toast__content").text(text);
            textToast.show();
            if (!(time>0)) {
                time = 1000;
            }
            setTimeout(function(){
                textToast.hide();
            }, time);
        }
        
        // Toast加载动画
        function loading(show, text){
            if (show) {
                loadingToast.find(".weui-toast__content").text(text);
                loadingToast.show();
            } else {
                loadingToast.find(".weui-toast__content").text("");
                loadingToast.hide();
            }
        }
        
        // 对话框
        function confirm(data, yes, cancel, def){
            if (def) {
                return window.confirm(data);
            } else {
                var dialog_title = dialog.find(".weui-dialog__title"),
                    dialog_body = dialog.find(".weui-dialog__bd"),
                    dialog_cancel = dialog.find(".dialog-cancel"),
                    dialog_yes     = dialog.find(".dialog-yes");
                if (data.title) {
                    dialog_title.text(data.title);
                } else {
                    dialog_title.text("确认要操作吗？");
                }
                if (data.body) {
                    dialog_body.text(data.body);
                } else if (message.vote_confirm) {
                    dialog_body.text(message.vote_confirm);
                } else {
                    dialog_body.text("请谨慎操作");
                }
                if (data.cancel) {
                    dialog_cancel.text(data.cancel);
                } else {
                    dialog_cancel.text("取消");
                }
                if (data.yes) {
                    dialog_yes.text("确认");
                }
                // 取消按钮
                dialog_cancel.on("click", function(){
                    dialog_cancel.off("click");
                    dialog.hide();
                    if (cancel && "function" === typeof(cancel)) {
                        cancel();
                    }
                });
                // 确认按钮
                dialog_yes.on("click", function(){
                    dialog_yes.off("click");
                    dialog.hide();
                    if (yes && "function" === typeof(yes)) {
                        yes();
                    }
                });
                
                dialog.show();
                
            }
        }


        // 获取最新
        function getNew(callback){
            var top = page_1.offset().top,
                top_container = container.css("margin-top"),
                height_banner = banner.height();

            // 执行回调
            if (callback) {
                callback();
            }
            
            // 填充元素
            add_waterfall(items, template_item_waterfall, true);

            
//            if ((top - top_container) >)
            
            // 锚点移动
//            goToAnchor($(".vote-panel"), $(".weui-tab__panel"));

            // 增加历史
            addHistory({"page":"new"}, "最新参赛", "#page=new");
        }
        // 获取排行
        function getOrder(callback){
            // 选项排序
            var items_order = [];
            for( var k in items) {
                items_order.push(items[k]);
            }
            items_order.sort(function(m,n){
                return n.vote - m.vote;
            });
            for( var i in items_order) {
                items_order[i].ranking = parseInt(i)+1;
            }
            
            // 填充元素
            add_item($("#page_2"), items_order, template_item_small, true);
            
            // 执行回调
            callback();
            
            // 增加历史
            addHistory({"page":"order"}, "投票排行", "#page=order");
        }
        // 获取Top10
        function getTop10(callback){
            // 选项排序
            items.sort(function(m,n){
                return n.vote - m.vote;
            });
            
            // 取前10
            var items_10 = {};
            
            for( var i in items) {
                if (i <= 2) {
                    items_10[i]=items[i];
                }
            }

            // 填充元素
            add_item($("#page_1_3"), items_10, template_item_big, true);

            // 执行回调
            callback();

            // 增加历史
            addHistory({"page":"top10"}, "TOP10", "#page=top10");
        }

        /**
         *  填充元素
         * @param con      容器
         * @param list     数据列表
         * @param template 模板函数
         * @param clear    是否清空
         * @param no_for   是否循环
         * @param callback 回调函数
         */
        function add_item(con, list, template, clear, no_for, callback){
            if (clear){
                con.html($(''));
            }
            if (true === no_for) {
                con.append(template(list, callback));
            } else {
                for( var i in list){
                    con.append(template(list[i], callback));
                }
            }

        }
        
        /**
         *  填充元素
         * @param con      容器
         * @param list     数据列表
         * @param template 模板函数
         * @param clear    是否清空
         * @param no_for   是否循环
         * @param callback 回调函数
         */
        function add_waterfall(list, template, clear, no_for, callback){
            if (clear){
                var falls = waterfall.children(".fall");
                falls.html('');
            }
            if (true === no_for) {
                template(list, callback)
            } else {
                for( var i in list){
                    template(list[i],callback);
                }
            }

        }
        
        
        
        // 搜索
        var $searchBar = $('#searchBar'),
            $searchResult = $('#searchResult'),
            $searchText = $('#searchText'),
            $searchInput = $('#searchInput'),
            $searchClear = $('#searchClear'),
            $searchCancel = $('#searchCancel');

        // 隐藏搜索提示栏
        function hideSearchResult(){
            $searchResult.hide();
            $searchInput.val('');
        }

        // 取消搜索
        function cancelSearch(){
//            hideSearchResult();
            $searchBar.removeClass('weui-search-bar_focusing');
            $searchText.show();
            page_1_4.text('');
            page_1_4.hide();
            page_current.show();
        }

        $searchText.on('click', function(){
            $searchBar.addClass('weui-search-bar_focusing');
            $searchInput.focus();
        });
        $searchInput
            .on('blur', function () {
                if(!this.value.length) cancelSearch();
            })
            .on('input', function(){
                var number = 0, result = [];
                if(this.value.length) {
                    // TODO:查询选项
                    // 数字提取
                    number = parseInt(this.value.replace(/[^0-9]/g,''));
                    for (var i in items) {
                        if (number > 0 && number === parseInt(items[i].number)) {
                            result.push(items[i]);
                        } else {
                            var val_arr = this.value.split(' ');
                            for(var j in val_arr) {
                                console.log(val_arr[j]);
                                console.log(items[i].title);
                                console.log(items[i].title.indexOf(val_arr[j]));
                                if (val_arr[j] && items[i].title.indexOf(val_arr[j]) >= 0) {
                                    result.push(items[i]);
                                }
                            }
                        }
                    }
                    
                    // 改变搜索提示内容
//                    add_item($searchResult, result, template_item_result, true);
//                    $searchResult.show();
                    
                    // 改变搜索结果内容
                    // 查找当前显示窗口
                    if (!page_current) {
                        pages_sub.each(function(i){
                            if ("block" === $(pages_sub[i]).css("display")) {
                                page_current = $(pages_sub[i]);
                                // 隐藏当前显示窗口
                                page_current.hide();
                                return false;
                            }
                        });
                    }
                    var callback = function(that){
                        // 关闭详情页面
                        page_1_4.text('');
                        page_1_4.hide();
                    };
                    
                    add_item(page_1_5, result, template_item_small_result, true, false, callback);
                    pages_sub.hide();
                    page_1_5.show();


                    // 增加历史
                    addHistory({"page":"search"}, "查找", "#search="+this.value);
                    
                } else {
                    $searchResult.hide();
                    
                    page_1_4.text('');
                    page_1_4.hide();
                    page_1_5.hide();
                    page_current.show();
                    
                    // 增加历史
                    addHistory({"page":"main"}, vote.title, " ");
                }
            });
        $searchClear.on('click', function(){
            hideSearchResult();
            $searchInput.focus();
        });
        $searchCancel.on('click', function(){
            cancelSearch();
            $searchInput.blur();
        });
        
        // 刷新数据
        function getData(){
            var data = {action:'getData', vote_id:vote.id},
                now = Date.parse(new Date())/1000;
            if (now - refresh >= refresh_time && Math.random() > refresh_prob) {
                refresh = now;
                $.get(
                    '/index.php/Vote/api',
                    data,
                    function(res){
                        vote = res.data.vote;
                        items = res.data.items;
                        freshData();
                    }
                );
            }
            
        }
        
        // 更新数据面板
        function freshData(){
            label_item_number.text(items.length);
            var votes = 0;
            for (var i in items) {
                votes += parseInt(items[i].vote);
            }
            label_vote_number.text(votes);
            label_vote_view.text(vote.view);
        }
        
        
        // 添加历史到浏览器
        function addHistory(data, title,url) {
//            console.log("add history: " + title + ", url: " + url);
            history.pushState(data, title, url);
        }
        window.onpopstate = function(event) {
//            console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
            if (!event.state){
                pages_main.hide();
                page_1.show();
                pages_sub.hide();
                page_1_1.show();
                page_sub_nav.removeClass("weui-bar__item_on");
                page_sub_nav_1.addClass("weui-bar__item_on");
                page_main_nav.removeClass("weui-bar__item_on");
                page_main_nav_1.addClass("weui-bar__item_on");
            } else {
                switch (event.state.page) {
                    case "order":
                        pages_main.hide();
                        page_2.show();
                        page_main_nav.removeClass("weui-bar__item_on");
                        page_main_nav_2.addClass("weui-bar__item_on");
                        break;
                    case "top10":
                        console.log('后退到top10');
                        pages_main.hide();
                        page_1.show();
                        pages_sub.hide();
                        page_1_3.show();
                        page_sub_nav.removeClass("weui-bar__item_on");
                        page_sub_nav_3.addClass("weui-bar__item_on");
                        break;
                    case "detail":
                        pages_main.hide();
                        page_5.show();
                        page_sub_nav.removeClass("weui-bar__item_on");
                        page_sub_nav_555ddClass("weui-bar__item_on");
                        break;
                        
                    case "chart":
                        pages_main.hide();
                        page_2.show();
                        page_main_nav.removeClass("weui-bar__item_on");
                        page_main_nav_2.addClass("weui-bar__item_on");
                        break;
                    case "illustrate":
                        pages_main.hide();
                        page_3.show();
                        page_main_nav.removeClass("weui-bar__item_on");
                        page_main_nav_3.addClass("weui-bar__item_on");
                        break;
                    case "prise":
                        pages_main.hide();
                        page_4.show();
                        page_main_nav.removeClass("weui-bar__item_on");
                        page_main_nav_4.addClass("weui-bar__item_on");
                        break;
                    case "main":
                    case "new":
                    case "home":
                    default:
                        pages_main.hide();
                        page_1.show();
                        pages_sub.hide();
                        page_1_1.show();
                        page_sub_nav.removeClass("weui-bar__item_on");
                        page_sub_nav_1.addClass("weui-bar__item_on");
                        page_main_nav.removeClass("weui-bar__item_on");
                        page_main_nav_1.addClass("weui-bar__item_on");
                        break;
                }
            }
        };

        function goToAnchor(anchor, page){
            console.log(page.offset().top);
            if(anchor){
                if (anchor.offset()) {
                    page.animate({
                        scrollTop: anchor.offset().top
                    }, 800);
                }
            }
        }
    });
    
</script>
</body>
</html>
